package com.example.myapplication;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.example.myapplication.ApiServices.HttpBinApiService;
import com.example.myapplication.interceptors.MyInterceptor;
import com.example.myapplication.tools.RequestTool;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;
import retrofit2.Retrofit;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class RequestActivity extends AppCompatActivity {

    private static final String TAG = "sun";
    private OkHttpClient okHttpClient;
    Retrofit retrofit;
    HttpBinApiService httpBinApiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request);
        okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyInterceptor()).build();
        //传个服务器地址BaseUrl
        retrofit = new Retrofit.Builder().baseUrl("http://www.httpbin.org/").build();
        httpBinApiService = retrofit.create(HttpBinApiService.class);
    }

    public void btn_getSync(View view) {
        new Thread(() -> {
            Request request = new Request.Builder().url("http://www.httpbin.org/get?a=1&b=2").build();
            Call call = okHttpClient.newCall(request);
            try {
                Response response = call.execute();
                Log.i(TAG, "btn_getSync: " + Objects.requireNonNull(response.body()).string());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void btn_getAsync(View view) {
        final Request request = new Request.Builder().url("http://www.httpbin.org/get?a=1&b=2").build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.i(TAG, "btn_getAsync: " + Objects.requireNonNull(response.body()).string());
                }
            }
        });
    }

    public void btn_postSync(View view) {
        new Thread(() -> {
            FormBody formBody = new FormBody.Builder().add("a", "1").add("b", "2").build();
            final Request request = new Request.Builder().url("http://www.httpbin.org/post").post(formBody).build();
            Call call = okHttpClient.newCall(request);
            try {
                Response response = call.execute();
                Log.i(TAG, "btn_postSync: " + Objects.requireNonNull(response.body()).string());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void btn_postAsync(View view) {
        FormBody formBody = new FormBody.Builder().add("a", "1").add("b", "2").build();
        final Request request = new Request.Builder().url("http://www.httpbin.org/post?").post(formBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.i(TAG, "btn_getAsync: " + Objects.requireNonNull(response.body()).string());
                }
            }
        });
    }

    public void btn_postFile(View view) {
        verifyStoragePermissions(this);
        OkHttpClient okHttpClient = new OkHttpClient();
        File file1 = new File("/storage/emulated/0/Download/1.txt");
        File file2 = new File("/storage/emulated/0/Download/2.txt");
        MultipartBody multipartBody = new MultipartBody.Builder()
                .addFormDataPart("file1", file1.getName(), RequestBody.create(file1, MediaType.parse("text/plain")))
                .addFormDataPart("file2", file2.getName(), RequestBody.create(file2, MediaType.parse("text/plain")))
                .addFormDataPart("a", "1")
                .build();
        final Request request = new Request.Builder().url("http://www.httpbin.org/post").post(multipartBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.i(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                Log.i(TAG, "btn_getAsync: " + Objects.requireNonNull(response.body()).string());
            }
        });
    }

    public void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            int REQUEST_EXTERNAL_STORAGE = 1;
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    Map<String, List<Cookie>> cookies = new HashMap<>();

    public void btn_postCookie(View view) {
        final OkHttpClient okHttpClient = new OkHttpClient().newBuilder().cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
                cookies.clear();
                cookies.put(httpUrl.host(), list);
            }

            @NotNull
            @Override
            public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                List<Cookie> cookies = RequestActivity.this.cookies.get(httpUrl.host());
                return cookies == null ? new ArrayList<Cookie>() : cookies;
            }
        }).build();
        new Thread() {
            @Override
            public void run() {
                //登录
                FormBody formBody = new FormBody.Builder().add("username", "342393585")
                        .add("password", "sunjiahao1226").build();
                Request request = new Request.Builder().url("https://www.wanandroid.com/user/login").post(formBody).build();
                Call call = okHttpClient.newCall(request);
                RequestTool.testRequestCallSync(call, "登录");
                //查看收藏列表
                Request request1 = new Request.Builder().url("https://www.wanandroid.com/lg/collect/usertools/json").build();
                Call call1 = okHttpClient.newCall(request1);
                RequestTool.testRequestCallSync(call1, "查看收藏");
            }
        }.start();
    }


    public void btn_postRetrofit(View view) {
        retrofit2.Call<ResponseBody> call = httpBinApiService.post("342393585", "sunjiahao1226");
        call.enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                try {
                    Log.i(TAG, "onResponse: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: " + t.getMessage());
            }
        });
    }

}